import React, { useEffect } from 'react'
import { NavBar, Form, Toast, Button, Input } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'
import { login } from '../../api/user'
import { store } from '../../stores'
// import userInfo from '../../stores/reducer/user'

export default function LoginMain () {
  const history = useHistory()
  const location = useLocation()
  const back = () => {
    history.goBack()
  }
  const onFinish = async (value: any) => {
    try {
      const res = await login(value)
      if (res.code === 200) {
        store.dispatch({ type: 'setToken', payload: res.data.token })
        // if (location.search) {
        //   console.log(location)
        //   history.push(location.pathname)
        //   window.location.reload()
        // }
        history.push('/layout/home')
        // window.location.reload()

        Toast.show({
          icon: 'success',
          content: '登录成功'
        })
      }
    } catch (error) {
      console.log(error)
    }
  }
  return (
    <div style={{ marginTop: '5px' }}>
      <NavBar onBack={back} style={{ background: 'white' }}>
        登录
      </NavBar>
      <Form
        layout='horizontal'
        initialValues={{
          loginname: '17704051019',
          password: '123456'
        }}
        footer={
          <Button
            block
            type='submit'
            color='primary'
            size='large'
            style={{
              background: '#c82519',
              borderRadius: '24px'
            }}
          >
            登录
          </Button>
        }
        onFinish={onFinish}
      >
        <Form.Item
          label='手机号'
          name='loginname'
          rules={[
            { required: true, message: '用户名不能为空!' },
            {
              validator: (_, value) => {
                const reg = /^[a-zA-Z0-9_-]{4,16}$/
                return reg.test(value)
                  ? Promise.resolve()
                  : Promise.reject('用户名必须是5-16位！')
              }
            }
          ]}
        >
          <Input placeholder='请输入' />
        </Form.Item>
        <Form.Item
          label='密码'
          name='password'
          rules={[
            { required: true, message: '密码不能为空!' },
            {
              validator: (_, value) => {
                const reg = /^[a-zA-Z0-9]{6,16}$/
                return reg.test(value)
                  ? Promise.resolve()
                  : Promise.reject('密码至少时6位！')
              }
            }
          ]}
        >
          <Input placeholder='请输入密码' type='password' />
        </Form.Item>
      </Form>
    </div>
  )
}
